import config from "../config/config";
import * as selectService from '../services/selectService';
import {refreshToken} from "../services/selectService";

export default {
  namespace: "selectModel",
  state: {
    collapsed: false,
    homeView: null,
    tokenModel: null,
    codeModel: null,
    pageLoading: false,
    themeDrawerVisible: false,
    themeColor: config.DEFAULT_THEME_COLOR,
    siderColor: config.DEFAULT_SIDER_COLOR,
    themeStyle: "sideMenu",
    selectedStyle: "theme",
    isBlockStyle: true,
    timeoutModalCount: 0,
    userInfoVisible: false,
    systemStatus: "login",
    applicationList: [],
    tenantAppVo: null,
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    }
  },
  effects: {
    *init({ payload: params }, { select, call, put }) {
      yield put({ type: "getCorrelateTeanatAndAppByUser", payload: {}});
    },

    *getCorrelateTeanatAndAppByUser({ payload: params }, { select, call, put }) {
      const userJson = sessionStorage.getItem("userInfo");
      let userObj = JSON.parse(userJson);
      const res = yield call(selectService.getCorrelateTeanatAndAppByUser, { userId: userObj.userId });
      if (res.code == "200") {
        yield put({ type: "updateState", payload: { tenantAppVo: res.data }});
      }
    },

    *getAllApplication({ payload: params }, { select, call, put }) {
      const res = yield call(selectService.getApplicationList, {});
      if (res.code == "200") {
        yield put({ type: "updateState", payload: { applicationList: res.data }});
      }
    },

    *logout({ payload: params }, { select, call, put }) {
      yield put({ type: "updateState", payload: { pageLoading: true }});
      const { userName, password } = window._USERINFO_ ? JSON.parse(window._USERINFO_) : JSON.parse(sessionStorage.userInfo);
      const res = yield call(selectService.logout, { userName, password });
      if (res.code == "200") {
        console.log("selectModel logout res => ", res);
      }
      yield put({ type: "updateState", payload: { pageLoading: false, paneTabs: [], activeHeadMenuKey: "home", activeSideMenuKey: null, systemStatus: "logout" }});
    },

    *refreshPage({payload: params}, {select, call, put}) {
      const tokenModel = {};
      const token = sessionStorage.getItem("token");
      window._TOKEN_ = token;
      const userInfo = sessionStorage.getItem("userInfo");
      window._USERINFO_ = userInfo;
      tokenModel["token"] = token;
      tokenModel["userInfo"] = userInfo;
      yield put({type: "updateState", payload: { tokenModel, systemStatus: sessionStorage.getItem("systemStatus") }});
    },

    *refreshToken({ payload: params }, { select, call, put }) {
      const res = yield call(selectService.refreshToken, params);
      console.log("selectModel refreshToken res => ", res);
      if (res.code == "200") {
        window._USERINFO_ = res.data;
        window._TOKEN_ = res.data.token;
        sessionStorage.token = window._TOKEN_;
        sessionStorage.userInfo = JSON.stringify(window._USERINFO_);
        yield put({ type: "updateState", payload: { tokenModel: res.data }});
      }
    },

    *handleTimeout({payload: params}, {select, call, put}) {
      const {dispatch} = params;
      let {timeoutModalCount} = yield select(state => state.selectModel);
      if (timeoutModalCount > 0) return;
      timeoutModalCount++;

      Modal.confirm({
        title: '提示',
        okText: "确认",
        cancelText: "取消",
        content: "离开时间太长，请重新登录！",
        onOk() {
          dispatch({type: "logout", payload: {}}).then(() =>
            window.location.href = "http://localhost:8000"
          );
        },
        onCancel() {
          timeoutModalCount--;
          dispatch({type: "updateState", payload: {timeoutModalCount}});
        },
      });
      dispatch({type: "updateState", payload: {timeoutModalCount}});
    },
  },
  subscriptions: {
    onListenIFrameMessage({ dispatch, history }) {
      window.addEventListener("message", function (e) {
        // 监听页面超时事件，确定后直接跳转到登陆界面
        console.log("selectModel Listener e => ", e);
        if (e.data && e.data.operateType == "timeout") {
          dispatch({type: "handleTimeout", payload: { dispatch }});
        }
      });
    },
    setup({ dispatch, history }) {
      const pathname = window.location.pathname;
      console.log("selectModel subscriptions setup pathname => ", pathname);
      if (pathname == "/app") {
        dispatch({type: "init", payload: {}});
      }
    },
  },
};
